package com.example.shoppingcenter.Service;

import com.example.shoppingcenter.Ai.ClipDrop.ImageVO;
import com.example.shoppingcenter.Config.CDconfig;
import com.example.shoppingcenter.POJO.Image;
import com.example.shoppingcenter.POJO.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.example.shoppingcenter.Mapper.cdMapper;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class cdService {
    @Resource
    private CDconfig cdConfig;

    @Resource
    private cdMapper cdMapper;

    public String getKey() {
        return cdConfig.getCd_key();
    }

    public Result saveImage(MultipartFile imageBlob, int userId) {
        byte[] imageBytes;
        try {
            imageBytes = imageBlob.getBytes();
        } catch (IOException e) {
            // 处理获取字节数组时的异常
            e.printStackTrace();
            return new Result(false, "获取字节数组时出错");
        }
        int res = cdMapper.saveImage(userId,imageBytes);
        Result result = new Result();
        if(res > 0) {
            result.setResult(true);
            result.setMessage("success");
        }else {
            result.setResult(false);
            result.setMessage("保存失败");
        }
        return result;
    }

    public List<ImageVO> getImagesByUserId(int userId){
        List<Image> imageList = cdMapper.getImageByUserId(userId);
        List<ImageVO> imageVOs = new ArrayList<>();
        for (Image image : imageList) {
            ImageVO imageVO = image.convert();
            imageVOs.add(imageVO);
        }
        return imageVOs;
    }

    public Result deleteImage(int imageId) {
        int res = cdMapper.deleteImage(imageId);
        Result result = new Result();
        if(res > 0){
            result.setMessage("删除成功");
            result.setResult(true);
        }else {
            result.setMessage("删除失败");
            result.setResult(false);
        }
        return result;
    }
}
